//
//  MLHttpHelper.m
//  Meili
//
//  Created by Robin on 15/12/29.
//  Copyright © 2015年 Robin. All rights reserved.
//

#import "MYHttpHelper.h"
#import "MYActionHelper.h"

NSString *const HttpCodeKey = @"code";
NSString *const HttpMessageKey = @"responseText";
const NSUInteger HttpRightCode = 0;

static const CGFloat TimeOutSec = 15.0;

@implementation MYHttpHelper

+(MYHttpHelper *)shareHelper
{
    static MYHttpHelper *helper = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        helper = [[MYHttpHelper alloc]init];
        [MLActionHelper actionWithHost:@"" client:@"ios" codeKey:HttpCodeKey rightCode:HttpRightCode msgKey:HttpMessageKey];
    });
    return helper;
}
#pragma mark - 非RAC请求
-(MYRequest *)postWithHost:(NSString *)host
                     url:(NSString *)url
                  params:(__kindof NSDictionary *)params
                 success:(successBlock)success
                  failed:(failedBlock)failed
{
    return [self noRac_requestWithMethod:@"POST" host:host url:url params:params success:success failed:failed];
}

-(MYRequest *)postWithUrl:(NSString *)url
                 params:(__kindof NSDictionary *)params
                success:(successBlock)success
                 failed:(failedBlock)failed
{
    return [self noRac_requestWithMethod:@"POST" host:nil url:url params:params success:success failed:failed];
}

-(MYRequest *)getWithHost:(NSString *)host
                    url:(NSString *)url
                 params:(__kindof NSDictionary *)params
                success:(successBlock)success
                 failed:(failedBlock)failed
{
    return [self noRac_requestWithMethod:@"GET" host:host url:url params:params success:success failed:failed];
}

-(MYRequest *)getWithUrl:(NSString *)url
                params:(__kindof NSDictionary *)params
               success:(successBlock)success
                failed:(failedBlock)failed
{
    return [self noRac_requestWithMethod:@"GET" host:nil url:url params:params success:success failed:failed];
}

-(MYRequest *)noRac_requestWithMethod:(NSString *)method
                         host:(NSString *)host
                          url:(NSString *)url
                       params:(__kindof NSDictionary *)params
                      success:(successBlock)success
                       failed:(failedBlock)failed
{
    MYRequest *req = [self requestWithMethod:method host:host url:url params:params success:success failed:failed];
    [RACObserve(req, state) subscribeNext:^(NSString *state) {
        if(req.succeed){
            success(req.output);
        }
        else if(req.failed){
            [UIWindow hideProgress];
            failed(req.error);
        }
        else if(req.cancled){
            [UIWindow hideProgress];
        }
    }];
    
    [[MLActionHelper sharedHelper] sendRequest:req];

    return req;
}

#pragma mark - RAC请求
-(MYRequest *)rac_postWithHost:(NSString *)host
                         url:(NSString *)url
                      params:(__kindof NSDictionary *)params
                     success:(successBlock)success
                      failed:(failedBlock)failed
{
    return [self rac_requestWithMethod:@"POST" host:host url:url params:params success:success failed:failed];
}

-(MYRequest *)rac_postWithUrl:(NSString *)url
                 params:(__kindof NSDictionary *)params
                success:(successBlock)success
                 failed:(failedBlock)failed
{
    return [self rac_requestWithMethod:@"POST" host:nil url:url params:params success:success failed:failed];
}

-(MYRequest *)rac_getWithHost:(NSString *)host
                        url:(NSString *)url
                     params:(__kindof NSDictionary *)params
                    success:(successBlock)success
                     failed:(failedBlock)failed
{
    return [self rac_requestWithMethod:@"GET" host:host url:url params:params success:success failed:failed];
}

-(MYRequest *)rac_getWithUrl:(NSString *)url
                params:(__kindof NSDictionary *)params
               success:(successBlock)success
                failed:(failedBlock)failed
{
    return [self rac_requestWithMethod:@"GET" host:nil url:url params:params success:success failed:failed];
}

-(MYRequest *)rac_requestWithMethod:(NSString *)method
                         host:(NSString *)host
                          url:(NSString *)url
                       params:(__kindof NSDictionary *)params
                      success:(successBlock)success
                       failed:(failedBlock)failed
{
    MYRequest *req = [self requestWithMethod:method host:host url:url params:params success:success failed:failed];
    req.racSignal = [[RACSignal createSignal:^RACDisposable *(id <RACSubscriber> subscriber) {
        [RACObserve(req, state) subscribeNext:^(NSString *state) {
            if(req.succeed){
                success(req.output);
                [subscriber sendNext:req.output];
                [subscriber sendCompleted];
            }
            else if(req.failed){
                [UIWindow hideProgress];
                failed(req.error);
                [subscriber sendError:req.error];
                [subscriber sendCompleted];
            }
            else if(req.cancled){
                [UIWindow hideProgress];
            }
        }];
        
        [[MLActionHelper sharedHelper] sendRequest:req];
        
        return [RACDisposable disposableWithBlock:^{
            [req cancle];
        }];
        
    }] setNameWithFormat:@"builder %@", req];

    return req;
}


-(MYRequest *)requestWithMethod:(NSString *)method
                         host:(NSString *)host
                          url:(NSString *)url
                       params:(__kindof NSDictionary *)params
                      success:(successBlock)success
                       failed:(failedBlock)failed
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:params];
    
    MYRequest *req = [MYRequest request];
#if isTest == 0
    req.SCHEME = @"https";
#endif
    //header头
//    NSMutableDictionary *header = [NSMutableDictionary new];

    //版本
//    NSString *version = [NSString stringWithFormat:@"ios%@",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]];
//    header[@"version"] = version;
//
//    //存在keychain的uuid，不可变
//    header[@"kid"] = [[MYAppHelper shareHelper] getDeviceId];
//    //存在本地的uuid，生命周期只有程序的生命周期
//    header[@"iid"] = [[MYAppHelper shareHelper] getUUID];
//    req.httpHeaderFields = [[NSDictionary alloc]initWithDictionary:header];
    
    req.METHOD = method;
    req.timeoutInterval = TimeOutSec;
    req.params = dict;
//    if(host && host.length > 0){
//        req.HOST = host;
//    }
    req.PATH = url;
    
    return req;
}

#pragma mark - method

+ (RACSignal *)emptySignal
{
    return [[RACSignal createSignal:^RACDisposable *(id <RACSubscriber> subscriber) {
        [subscriber sendError:[NSError errorWithDomain:MYEmptyDomain code:MYErrorCodeCancle userInfo:nil]];
        [subscriber sendCompleted];
        return [RACDisposable disposableWithBlock:^{}];
    }] setNameWithFormat:@"prevent nil"];
}

+ (RACSignal *)errorSignalWithMsg:(NSString *)msg
{
    return [[RACSignal createSignal:^RACDisposable *(id <RACSubscriber> subscriber) {
        [subscriber sendError:[NSError errorWithDomain:MYErrorDomain code:MYErrorCodeCancle userInfo:@{MYErrorMsgKey : msg}]];
        [subscriber sendCompleted];
        return [RACDisposable disposableWithBlock:^{}];
    }] setNameWithFormat:@"error condition"];
}

+ (BOOL)isSuccessOfDic:(NSDictionary *)dict {
    [UIWindow hideProgress];
    if (!dict) {
        return NO;
    }
    NSUInteger code = [dict[HttpCodeKey] integerValue];
    NSString *text = dict[HttpMessageKey];
    
    if (code == HttpRightCode) {
        return YES;
    }
    
    [UIWindow showFailedMsg:text];
    return NO;
}

+ (BOOL)reqSuccessOfDic:(NSDictionary *)dict {
    if (!dict) {
        return NO;
    }
    NSUInteger code = [dict[HttpCodeKey] integerValue];
    return code == HttpRightCode;
}

@end
